package dao;

import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import entity.ProductDB;

public class DBdao {
	private static String driverName = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/shopping";
	private static String userName = "root";
	private static String password = "kimheechul";
	public static void registerDriver() {
		try {
			Class.forName(driverName);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("找不到驱动");
		}
	}

	public static Connection getConnection() throws SQLException {
		Connection conn = null;
		System.out.println("正在连接数据库...");
		conn = DriverManager.getConnection(url, userName, password);
		System.out.println("数据库已连接!");
		return conn;

	}

	public static void closeConnection(Connection conn) {
		System.out.println("正在释放所有资源...");
		
			if (conn != null) {
				try {
					conn.close();
					conn = null;
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		
	}
	public static void realeaseAll(ResultSet rs,Statement st,Connection conn){
		if(rs!=null){
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (st!=null){
			try {
				st.close();
				st = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		closeConnection(conn);
	}
	//public List<ProductDB> main(){
	public static List<ProductDB> readproductDB(){
		List<ProductDB> list = new ArrayList<ProductDB>();
		Connection con=null;
		Statement stat = null;
		String sql = "select * from product";//表中有id,name,price
		try{
			con = DBdao.getConnection();
			stat = con.createStatement();
			ResultSet rs = stat.executeQuery(sql);
			while(rs.next()){
				int id = rs.getInt("id");
				String name = rs.getString("name");
				double price = rs.getDouble("price");
				System.out.format("该记录的id=%d,姓名=%s\n",id,name);
				ProductDB product=new ProductDB(id,name,price);
				list.add(product);
			}
		}catch (SQLException sqle) {
			sqle.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBdao.closeConnection(con);
		}
		return list;	
	}
	public static void main(String[] args) {
		readproductDB();
	}
}
